<script setup lang="ts">
import { defineProps, defineEmits, ref, watch } from 'vue';

const props = defineProps<{
  todo: Object;   //对象
  id: number;
  completed: boolean;
}>();

const emit = defineEmits<{
  (e: 'remove', id: number): void;
  (e: 'update', id: number, newTodo: string): void;
  (e: 'toggleComplete', id: number): void;
}>();

const iscompleted = ref(props.completed);
const editedTodo = ref(props.todo);

watch(() => props.todo, (newTodo) => {
  editedTodo.value = newTodo;
});

const isEditing = ref(false);

const handleUpdate = () => {
  emit('update', props.id, editedTodo.value);
  isEditing.value = false;
};

const toggleEdit = () => {
  isEditing.value = true;
};

const toggleComplete = () => {  
  iscompleted.value = !iscompleted.value;
  emit('toggleComplete', props.id);
};

const clickCount = ref(100);
</script>

<template>
  <!-- Todo item container with conditional class for completed state -->
  <li v-highlight class="todo-item" :class="{ 'completed': completed }"> 
    <!-- Checkbox to toggle completion state -->
    <!-- <input type="checkbox" :checked="completed" @change="toggleComplete" class="todo-checkbox" /> -->
    <el-checkbox v-model="iscompleted"  size="large"  @change="toggleComplete"/>
    <!-- Editable input field for editing the todo item -->
    <input v-if="isEditing" v-model="editedTodo" type="text" class="todo-input" @blur="handleUpdate" @keydown.enter="handleUpdate" />
    <!-- Displayed text of the todo item, double-click to edit -->
    <span v-else @dblclick="toggleEdit" class="todo-text">{{ editedTodo.title }}</span>
    <!-- Button to remove the todo item -->
    <!-- <button @click="emit('remove', id)">Remove</button> -->

    <el-button type="danger" @click="emit('remove', id)">Remove</el-button>
    <!-- Update button visible only when editing -->
    <button v-if="isEditing" @click="handleUpdate">Update</button>

    <slot :clickCount="clickCount"></slot>
  </li>
</template>

<style scoped>
/* Base style for todo item */
.todo-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem;
  border-bottom: 1px solid #ccc;
}

/* Style for completed todo item text */
.todo-item.completed .todo-text { 
  text-decoration: line-through;
}

/* Style for buttons in todo item */
.todo-item1 button {
  padding: 0.3rem 0.6rem;
  border: none;
  background-color: #ff4d4f;
  color: white;
  border-radius: 4px;
  cursor: pointer;
}

/* Hover effect for buttons */
.todo-item1 button:hover {
  background-color: #ff3b30;
}

/* Style for editable input field */
.todo-item .todo-input { 
  padding: 0.3rem;
  border: 1px solid #ccc;
  border-radius: 4px;
  flex-grow: 1;
  margin-right: 0.5rem;
}

/* Style for displayed text of the todo item */
.todo-item .todo-text {
  flex-grow: 1;
  margin-right: 0.5rem;
  cursor: pointer;
}

/* Style for checkbox in todo item */
.todo-item .todo-checkbox {
  margin-right: 0.5rem;
}
</style>